import { Effect, Reducer, Subscription } from 'umi';
import { api1 } from '@/utils/api';

export interface ListItemType {
  goodsClass: string;
  goodsId: number;
  goodsName: string;
  goodsAddress: string;
  goodsStar: string;
  goodsImg: string;
  goodsSale: number;
}

export interface IndexModelState {
  name: string;
  count2: number;
  list: ListItemType[];
}

export interface IndexModelType {
  // todo 如果一个变量的值是一个固定的字符串不会变的，可以直接拿那个字符串作为数据类型
  namespace: 'index';
  state: IndexModelState;
  effects: {
    query: Effect;
    load: Effect;
  };
  reducers: {
    save: Reducer;
    increment: Reducer;
    syncLoad: Reducer;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  // todo 命名空间的名字
  namespace: 'index',

  // todo 仓库数据
  state: {
    name: '',
    count2: 0,
    list: [],
  },

  // todo 里面写异步方法，相当于vuex的actions
  effects: {
    *query({ payload }, { call, put }) {},
    *load({ payload }, { call, put }) {
      const res = yield call(api1);
      // console.log(res);
      yield put({ type: 'syncLoad', payload: res });
    },
  },

  // todo 里面写同步方法，相当于vuex的mutations，只能在这里改变数据
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    increment(state, action) {
      return {
        ...state,
        count2: state.count2 + 1,
      };
    },
    syncLoad(state, action) {
      return {
        ...state,
        list: action.payload.data,
      };
    },
  },

  // todo 可以做url监听
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        // console.log(pathname);
        if (pathname === '/typescript') {
          dispatch({
            type: 'load',
          });
        }
      });
    },
  },
};

export default IndexModel;
